package com.jl.rocketmq.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * @description: 消费者
 * @author: jl
 * @create: 2021/4/5 12:07
 */
public class Consumer2 {

    public static void main(String[] args) throws Exception{
        //创建消费者： 使用push模式
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(RocketmqConstant.producerGroup1);
        consumer.setNamesrvAddr(RocketmqConstant.mq_namesrv_cluster);

        //设置消息消费模型：默认就是集群模式
        consumer.setMessageModel(MessageModel.CLUSTERING);
//        consumer.setMessageModel(MessageModel.BROADCASTING);

        //订阅消息 每个consumer关注一个topic.  过滤器 * 表示不过滤
        consumer.subscribe(RocketmqConstant.topic1, "*");
//        consumer.subscribe(RocketmqConstant.topic1, RocketmqConstant.tag_sync);
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    String topic = msg.getTopic();
                    byte[] body = msg.getBody();
                    String content = new String(body);
                    String bornHostString = msg.getBornHostString();

                    System.out.println("topic:" + topic +", content=" + content + ", host="+bornHostString);
                }
                //默认情况下这条消息只会被一个consumer消费到  点对点
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //启动消费者
        consumer.start();
        System.out.println("consumer start------------");


    }
}
